package com.example.booksystem.dao;

import com.example.booksystem.bean.User;
import com.example.booksystem.utils.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDao {

    //查询用户
    public User getUser(String name,String pwd){
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        User user = new User();

        try {
            connection = DBUtil.getConnection();
            String sql = "select * from user where name = ? and pwd = ? and state = 1";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,name);
            preparedStatement.setString(2,pwd);
            resultSet = preparedStatement.executeQuery();
            while (resultSet.next()){
                user.setId(resultSet.getLong(1));
                user.setName(resultSet.getString(2));
                user.setPwd(resultSet.getString(3));
                user.setState(resultSet.getLong(4));;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.close(connection,preparedStatement,resultSet);
        }
        return user;
    }

    //修改密码
    public int modifyPwd(long id,String pwd){
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        int result = 0;

        try {
            connection = DBUtil.getConnection();
            String sql = "update user set pwd = ? where id = ?";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,pwd);
            preparedStatement.setLong(2,id);
            result = preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.close(connection,preparedStatement,resultSet);
        }
        return result;
    }

    //增加用户
    String sql = "insert into user (name,pwd,state) values(?,?,?) ";
    //preparedStatement.executeUpdate();

    //删除用户
    //delete from user where id = ?
}
